<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
<div>
          <el-checkbox-group v-model="checkboxVal">
            <el-checkbox class="col_check" v-for="(v,i) in formTheadOptions" :key="i" :label="v.field">{{v.title}}</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-table size="mini" :data="mtb.data"  v-loading.body="listLoading" border style="width: 100%" highlight-current-row @row-dblclick="handleUpdateRow" >
          <el-table-column v-for="(v,i) in mtb.columns" align="center" :key="i" :prop="v.field" :label="v.title" :align="v.align" :width="v.width">
            <template slot-scope="scope">
              <span v-if="scope.row.isSet && v.edit">
                  <el-input size="mini" :placeholder="'请输入'+v.title" v-model="mtb.sel[v.field]"></el-input>
              </span>
              <span v-else >{{scope.row[v.field]}}</span>
              <!--<span v-else @dblclick="handleUpdate(scope.row,scope.$index,true)">{{scope.row[v.field]}}</span>-->
            </template>
          </el-table-column>
          <!--<el-table-column fixed="right" label="操作" width="100">-->
          <el-table-column  label="操作" width="100"  fixed="right">
            <template slot-scope="scope">
                            <button id="ebtn" @click="handleUpdate(scope.row)"  :class="scope.row.isSet?'el-tag el-tag--mini el-tag--success':'el-tag el-tag--mini'" style="cursor: pointer;">
                                {{scope.row.isSet?'保存':"修改"}}
                            </button>
              <button v-if="!scope.row.isSet"  @click="handleDelete(scope.row)" class="el-tag el-tag--danger el-tag--mini" style="cursor: pointer;">
                                删除
                            </button>
              <button v-else class="el-tag  el-tag--mini  el-tag--info" style="cursor: pointer;" @click="handleUpdate(scope.row,true)">
                                取消
                            </button>
            </template>

          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="24">
        <div class="el-table-add-row" style="width: 99.2%;" @click="addMasterUser()"><span>+ 添加</span></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {disableBtn, df, $err, $suc, ERRS, SUCS,$msg} from '@/utils'
import {fetchGet, createOne, deleteOne, deletePost, getOne, rolesAll, updateOneNoId} from '@/api/common'
const _ = require('lodash');
//https://www.jianshu.com/p/79f39f2c1382
//https://www.jianshu.com/p/33175c3a6ba4
export default {
  name: 'tablecom',
  props: {
    list: Array,
    columns:Array,
    listLoading:Boolean,
  },
  data:function () {
    return {
      count:1,
      mtb: {
        data:this.list, //数据
        sel: null,//选中行
        columns: this.columns,// columns: [{edit:false, field: "name", title: "名称", width: 50 ,align:"center" }, ]
      },
      temp:{},

      key:1,// table key
      // formTheadOptions: ['apple', 'banana', 'orange'],
      formTheadOptions: [], //选择项
      formTheadval: [], //选择值
      defaultFormThead: [], //默认选中值
      checkboxVal: [], // 当前多选选中 checkboxVal
      formThead: [] // thead关联表中当前显示的col

    }
  },

  watch:{
    list(newdata){
      this.mtb.data=newdata;
    },
    checkboxVal(valArr) {
      console.log(valArr);
      console.log(this.mtb.columns);
      this.mtb.columns=this.columns.filter((i) =>{
          return valArr.indexOf(i.field) >= 0
        })
      this.key = this.key + 1// 为了保证table 每次都会重渲 In order to ensure the table will be re-rendered each time
    }

  },
  mounted(){
/*    document.oncontextmenu = function(){
      return false;
    }*/
    //取出列
    this.formTheadOptions=this.columns.map((v) =>{ return {field:v.field,title:v.title}});
    // this.formTheadOptions=[ {field:v.field,title:v.title}];
    this.defaultFormThead=this.formTheadOptions.map(v =>  v.field); //默认全选中值
    this.checkboxVal=this.defaultFormThead
    // this.formThead=this.columns.filter((v) => this.checkboxVal.indexOf(v.field) >= 0);

  },

  methods: {

    //删除
    handleDelete(row) {
      this.$msgbox({
        message: '确定要删除该层级及所有子级吗? 该操作不可逆,请谨慎操作!!!',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(action => {
        deleteOne('codeExplains', {id: row.id}).then(res => {
          if (res.data.code === 0) {
            $suc('删除成功!')
            this.$parent.getList();
          } else {
            ERRS(res.data.message)
          }
        })
      });
    },

    handleUpdateRow(row, event, column) {
      this.handleUpdate(row)
    },
    //详情修改
    handleUpdate(row,cancel=false) {
      console.log(row,cancel);
      // handleUpdate(scope.row,scope.$index,true)   handleUpdate(row, index, flag)
      //点击修改 判断是否已经保存所有操作
      for (let i of this.mtb.data) {
        if (i.isSet && i.id != row.id) {
          this.$message.warning("请先保存当前编辑项");
          return false;
        }
      }
      //是否点击的取消操作 cancel=true
      if (cancel) {
        return row.isSet = !row.isSet;
      }
      //提交数据
      if (row.isSet) {
        let data = JSON.parse(JSON.stringify(this.mtb.sel));
        //项目是模拟请求操作  自己修改下
        this.temp = {
          id: data.id,
          codeNo: data.codeNo,
          explainText: data.explainText,
        };
        if (row.parentCodeExplain) //有子级加
          this.temp.parentId = row.parentCodeExplain.id

        disableBtn('ebtn');
        updateOneNoId('codeExplains', this.temp).then(res => {
          // console.log(res);
          if (res.data.code === 0) {
            for (let k in data) row[k] = data[k];
            row.isSet = false;
            $suc('更新成功!')
          } else {
            ERRS(res.data.message)
          }
        })
      } else {
        this.mtb.sel = JSON.parse(JSON.stringify(row));
        row.isSet = true;
      }

    },
    //读取表格数据
    readMasterUser() {
      //根据实际情况，自己改下啊
      this.mtb.data.map(i => {
        i.id = this.generateId();//模拟后台插入成功后有了id
        i.isSet=false;//给后台返回数据添加`isSet`标识
        return i;
      });
    },
    //添加账号
    addMasterUser() {
      for (let i of this.mtb.data) {
        if (i.isSet) return this.$message.warning("请先保存当前编辑项");
      }
      let j = { id: 0, "type": "", "addport": "", "user": "", "pwd": "", "info": "", "isSet": true, "_temporary": true };
      this.mtb.data.push(j);
      this.mtb.sel = JSON.parse(JSON.stringify(j));
    },




  }
}
</script>

<style scoped>
  .el-table-add-row {
    margin-top: 10px;
    width: 100%;
    height: 34px;
    border: 1px dashed #c1c1cd;
    border-radius: 3px;
    cursor: pointer;
    justify-content: center;
    display: flex;
    line-height: 34px;
  }

</style>
